<?php
!defined('IN_FENGTOPsso') && exit('Access Denied');

class LogIn extends Base{
	private $userName;
	private $userPwd ;
	private $captcha ;
	private $fetcher ;
	
	public function __construct() {
		parent::__construct();
		$this->userName = daddslashes($_POST['userName']);
		$this->userPwd  = daddslashes($_POST['userPwd']) ; 
		$this->captcha  = daddslashes($_POST['captcha']) ; 
		$this->fetcher  = daddslashes($_POST['fetcher']) ; 
	}
	
	public function checkIn() {
		//已经登录
		//用户状态不对（注销，禁用）
//return $_SESSION['checkpic'][1];
//		if($this->captcha != $_SESSION['checkpic'][1]){
//			return 1; //验证码不正确
//		}
	}
	
	public function selectSql() {
		$selectSql = "SELECT * 
					    FROM `{$GLOBALS['_FENGTOPsso']['db']['1']['tablepre']}user_".substr(md5($this->userName), 0, 2)."` 
					   WHERE `username`='$this->userName'
					     AND `password` = '".md5($this->userPwd)."'";
//echo $selectSql;
//setcookie("uid123"            , $selectSql        , 0, "/", "fengtop.net");
		$result = $this->mysqldb->GetOne($selectSql);
//print_r($result);
		if (!empty($result)) {
			$result['ticket'] = md5($GLOBALS['PHPSESSID']);
			$_SESSION['FOnlineUser'] = $result;
			$this->insertOnLine();
			$this->setClientCookie($result);
			//echo json_encode($result);
		}else {
			//echo "登录失败！";
			return -1;
		}
	}
	
	private function insertOnLine() {
		$this->getStartTime();
		
		//检查是否已登录
		if ($this->selectOnLine()) {
			$this->deleteOnLine();
		}
		
		$insertOnlineSql = "INSERT INTO `{$GLOBALS['_FENGTOPsso']['db']['1']['tablepre']}onlineuser` (
 								        `ticket` ,
									    `username` ,
									    `expiry` ,
									    `data` )
								VALUES (
 										'".$_SESSION['FOnlineUser']['ticket']."',
 										'".$this->userName."',
 										'".$GLOBALS['sec']."',
 										'".json_encode($_SESSION['FOnlineUser'])."'
										);";
//echo $insertOnlineSql;
		$this->mysqldb->Query($insertOnlineSql);
	}
	
	private function getStartTime() {
		list ( $GLOBALS['usec'], $GLOBALS['sec'] ) = explode ( " ", microtime () );
	}
	
	private function selectOnLine() {
		$selectOnlineSql = "SELECT count(*)
		                      FROM `{$GLOBALS['_FENGTOPsso']['db']['1']['tablepre']}onlineuser`
		                     WHERE `ticket` = '".$_SESSION['FOnlineUser']['ticket']."'";
		return $this->mysqldb->GetOne($selectOnlineSql);
	}
	
	private function deleteOnLine() {
		$deleteOnlineSql = "DELETE FROM `{$GLOBALS['_FENGTOPsso']['db']['1']['tablepre']}onlineuser` WHERE `onlineuser`.`ticket` = '".$_SESSION['FOnlineUser']['ticket']."'";
		$this->mysqldb->Query($deleteOnlineSql);
	}
	
	private function setClientCookie($result) {
//echo "result";print_r($result);
		require_once FENGTOPsso_DIR.'/public/CookieHandle.class.php';
		$clientCookie = new CookieHandle();
		$clientCookie->setClientCookie($result);
	}
	
	public function setFetcher(){
		$GLOBALS['fetcher'] = $this->fetcher;
	}
}

?>